import { message } from "antd";
import axios from "axios";

class myAxios {

	baseUrl = "http://localhost:8081/";

	constructor() {
		axios.defaults.withCredentials = true
		this.myAxios = axios
	}

	judge(data,resolve ){
		//捕获所有错误请求
		if (data.code === 5002) {
			localStorage.removeItem("isLogin");
			localStorage.removeItem("adminToken");
			window.location.reload();
		}        
		if((data.code===1002) || (data.code===2003) || (data.code===2002 ) || (data.code===4002) || (data.code===3002) ||(data.code===6002) ){
			message.error(data.message)
		}
		//成功请求交给各个组件处理
		else {
			resolve(data)
		}

}

	post(url, body, params) {
		let token = window.localStorage.getItem("adminToken");
		return new Promise((resolve, reject) => {
			this.myAxios({
				url: this.baseUrl + url,
				method: 'post',
				data: body,
				headers: {
					Authorization: "Bearer " + token
				}
			})
			.then((res) => {
				if (res.status === 200) {
					const data = res.data
					this.judge(data,resolve)
				} else {
					reject(new Error("状态值不是200"))
				}
			})
			.catch()
		})
		
	}

	get(url, params) {
		let token = window.localStorage.getItem("adminToken");
		if(params===undefined){
			params='';
		}
		return new Promise((resolve, reject) => {
			this.myAxios({
				url:this.baseUrl + url,
				method:'get',
				params:
					params
				,
				headers: {
					Authorization: "Bearer " + token
				}
				})
			.then((res) => {
				if (res.status === 200) {
					const data = res.data
					this.judge(data,resolve)
				} else {
					reject(new Error("状态值不是200"))
				}
			})
			.catch()
		})
	}

  download(url,data,fileType){
	 let token = window.localStorage.getItem("adminToken");
	 const res=axios
	 	.request({
		url: this.baseUrl+url,
		method: "post",
		data: data, // 筛选列表的请求参数
		headers: {
			Authorization: "Bearer " + token
		},
		responseType: "blob",
	  })
	  .then((res) => {
		const data = res.data;
		let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
		var a = document.createElement("a");
		document.body.appendChild(a);
		a.href = url;
		a.download =fileType ;
		a.click(); // 模拟点击下载
		window.URL.revokeObjectURL(url);
	  });

  }

  delete(url,param) {
	let token = window.localStorage.getItem("adminToken");
	return new Promise((resolve,reject)=>{
		this.myAxios({
			url:this.baseUrl + url,
			method:'delete',
			headers: {
				Authorization: "Bearer " + token
			},
			params:
				param,
			})
		.then(res=>{
			if(res.status===200){
				const data=res.data;
				this.judge(data,resolve)
			}
			else{
				reject(new Error("状态码不是200"))
			}		
		})
		.catch(res=>{
			console.log(res);
		})
	})
}

}

export default new myAxios();